package com.marvels.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.dragon.common.util.PropertiesLoadUtil;
import com.itextpdf.text.pdf.BaseFont;

import cn.hutool.core.io.file.FileReader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 合同模板解析工具类
 * @author Administrator
 *
 */
public class ContractParseUtil {

	public static String parseContractTemplate(String ftlPath,String fileName,Object data) throws IOException, TemplateException{
		Configuration configuration = new Configuration();
		
        configuration.setDirectoryForTemplateLoading(new File(ftlPath));
        configuration.setDefaultEncoding("UTF-8");
        // 获取或创建一个模版。  
        Template template = configuration.getTemplate(fileName);
        
        // 获取html静态页面文件
        StringWriter strWrite = new StringWriter();
        template.process(data, strWrite);
        strWrite.close();
        return strWrite.getBuffer().toString();
	}
	
//	public static void main(String[] args) {
//		try {
//			String ftlPath = "D:/workspasefj/marvels-core-v2/branches/marvels-core-v2-1.0.0/marvels-core-approve/resources/VideoCheck/ftl";
//			String fileName = "four_loan_contract_template.ftl";
//			HashMap<String,Object> map = new HashMap<String, Object>();
//			map.put("contractYear", "2017");
//			
//			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
//			Map<String,String> param = new HashMap<String,String>();
//			param.put("ruleName", "经理人");
//			param.put("ruleResult", "1.0");
//			
//			list.add(param);
//			param = new HashMap<String,String>();
//			param.put("ruleName", "经理人2");
//			param.put("ruleResult",null);
//			
//			list.add(param);
//			map.put("ruleList", list);
//			
//			
//			//System.out.println(ContractParseUtil.parseContractTemplate(ftlPath,fileName,map));
//			//ContractParseUtil.parseContractTemplate(ftlPath,fileName,map);
//			//,"C:/Users/user/Desktop/更新需求/宝生/"
//			/*String html = test("D");
//			System.out.println(html);
//			File file = new File("E:\\test.html");
//			
//			BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//			bw.write(html);*/
//
////			System.out.println();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//	}
	public static void htmlToPdf(String html,String baseDir, String fileName) throws Exception {
		File directory = new File(baseDir);
		if(!directory.exists()){
			directory.mkdirs();
		}
//		String outputFile = baseDir + fileName;
		File file = new File(baseDir, fileName);
		OutputStream os = new FileOutputStream(file);
		ITextRenderer renderer = new ITextRenderer();
		ITextFontResolver fontResolver = renderer.getFontResolver();
		fontResolver.addFont(PropertiesLoadUtil.getPropertiesValue("font_path", "resource.properties"),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		renderer.setDocumentFromString(html);
		renderer.layout();
		renderer.createPDF(os);
		os.close();
	}
	
//	public static void main(String[] args) {
//	String htmlFile = "E:\\frank\\project\\marvels-core-v2-simple-1.3.0\\marvels-core-approve\\html.text";
//	try {
//		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile)));
//		StringBuilder sb = new StringBuilder();
//		String line = null;
//		while(null != (line=br.readLine())) {
//			sb.append(line).append("\r\n");
//		}
//		br.close();
//		htmlToPdf(sb.toString(),"E:\\frank\\project\\marvels-core-v2-simple-1.3.0\\marvels-core-approve","aaa.pdf");
//	} catch (Exception e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//	private static String test(String compactType){
//		Map<String,Object> resultMap = new HashMap<String,Object>();
//		String[] ymd = DateUtil.getDateYYYY_MM_DD(Calendar.getInstance().getTime()).split("-");
//		resultMap.put("contractYear", ymd[0]);
//		resultMap.put("contractMonth", ymd[1]);
//		resultMap.put("contractDay", ymd[2]);
//		//申请人姓名
//		resultMap.put("borrower", "何立超");
//		//申请人身份证编号
//		resultMap.put("borrowerCardId", "4251365425133654522");
//		//申请人地址
//		resultMap.put("borrowerAddress", "申请人地址信息");
//		//申请人电话
//		resultMap.put("borrowerCellPhnone", "18666224263");
//		//还款卡号
//		resultMap.put("borrowerBankCardNo", "622254210236251");
//		//借款用途
//		resultMap.put("loanUse", "测试");
//		String templateName = null;
//		//双方协议需要参数
//		if(StringUtils.equalsIgnoreCase(compactType, "D")){
//			//查询咨询费
//			resultMap.put("counselFee", "10");
//			
//			//查询管理费
//			resultMap.put("managementFee", "0.1");
//			
//			//先查询是否已经有合同编号AcLoanApplyInfo
//			String compactCode = null;
//			if(StringUtils.isEmpty(compactCode)){
//				compactCode = "CT-XD-01-"+ymd[0]+ymd[1]+"-"+"1203251";
//			}
//			resultMap.put("compactCode", compactCode);
//			
//			templateName = "two_loan_contract_template.ftl";
//		}else if(StringUtils.equalsIgnoreCase(compactType, "F")){
//			//四方协议所需参数
//			//核定金额大写
//			resultMap.put("loanCapitalUpper", "一百元");
//			//核定金额小写
//			resultMap.put("loanCapitalLower", new BigDecimal("100.00"));
//			//贷款期数
//			resultMap.put("loanPeriod", 24);
//			//贷款发放Y-M-D日   --预计时间  当前时间+2天
//			Date borrowIssueDate = DateUtils.add(Calendar.getInstance().getTime(), Calendar.DAY_OF_MONTH, 2);
//			String[] borrowIssueDateStr = DateUtils.getDateYYYY_MM_DD(borrowIssueDate).split("-");
//			resultMap.put("borrowIssueYear", borrowIssueDateStr[0]);
//			resultMap.put("borrowIssueMonth", borrowIssueDateStr[1]);
//			resultMap.put("borrowIssueDay", borrowIssueDateStr[2]);
//			//贷款到期Y-M-D日  预计发放日月份+期数
//			Date borrowExpireDate = DateUtils.add(Calendar.getInstance().getTime(), Calendar.MONTH, 24);
//			String[] borrowExpireDateStr = DateUtils.getDateYYYY_MM_DD(borrowIssueDate).split("-");
//			resultMap.put("borrowExpireYear", borrowExpireDateStr[0]);
//			resultMap.put("borrowExpireMonth", borrowExpireDateStr[1]);
//			resultMap.put("borrowExpireDay", borrowExpireDateStr[2]);
//			//查询利率编号
//			//计算年利率
//			String yearRate = (new BigDecimal("0.012").doubleValue()*100)+"%";
//			resultMap.put("yearRate", yearRate);
//			
//			templateName = "four_loan_contract_template.ftl";
//		}
//		String ftlPath = "E:\\java_project\\Fintech\\Fintech-bo\\WebRoot\\entity\\VideoCheck\\ftl";
//		try {
//			return ContractParseUtil.parseContractTemplate(ftlPath, templateName, resultMap);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (TemplateException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return "";
//	}
}
